<template>
<Cascader v-bind="$attrs" v-on="$listeners" :data="data" :load-data="loadData" v-model="val" :placeholder="placeholder"></Cascader>
</template>

<script>
import {
    transformTozTreeFormat
} from '@/utils/tool'

export default {
    props: {
        //只接收行政区域id
        value: {
            type: [String, Array, Number]
        },
        level: {
            type: Number,
            default: 0
        },
        auth: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            data: [],
            val: [],
            placeholder: "数据加载中...",
            areaLevel: [{
                id: 10000007770004,
                name: "国"
            }, {
                id: 10000007770005,
                name: "省/直辖市"
            }, {
                id: 10000007770006,
                name: "市/市辖区"
            }, {
                id: 10000007770007,
                name: "区/县"
            }, {
                id: 10000007770008,
                name: "街道/乡镇"
            }, {
                id: 10000007770009,
                name: "社区/村"
            }, {
                id: 10000007770010,
                name: "网格/组"
            }]
        }
    },
    computed: {
        areapath: function () {
            if (this.auth) {
                return JSON.parse(window.localStorage.getItem("userInfo")).areaid
            } else {
                return "100000000000"
            }
        }
    },
    watch: {
        value: "initData"
    },
    methods: {
        async getData(pid) {
            let res = await this.$api.area.getAreaByPid({
                pid: pid
            });

            res.rows.map(area => {
                area.value = area.id
                area.label = area.areaname
                area.children = []
                area.loading = false
            })

            return res
        },
        //获取初始的数据
        async loadData(item, callback) {
            item.loading = true;

            let res = await this.getData(item.id)
            if (res.total != 0) {
                item.children.push(...res.rows)

                callback()
                item.loading = false;
            } else {
                item.loading = false;
                delete item.loading
            }
        },
        initData(val){
            if(val == "" || val == undefined){
                this.val = []
            }
        }
    },
    async created() {
        let res = await this.getData(this.areapath)

        this.data = res.rows

        this.placeholder = "请选择"
    }
}
</script>

<style lang="less" scoped>

</style>
